<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/9
 * Time: 13:49
 */
namespace app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
session_start();

class Login extends Controller
{
    /*
     * 用户登录界面
     * */
    public function login()
    {
        // 返回登录页
        return $this->fetch();
    }

    /*
     * 用户登录验证
     * */
    public function sessions()
    {
        $name = $_POST['username'];
        $password = $_POST['pass'];
        $userInfo = db('admin')->where('name',$name)->find();
        $level = $userInfo['level'];
        $rbacList = array();

        if (!password_verify($password, $userInfo['password'])) {
            $this->redirect(url("admin/Login/login"));
        }
        // 验证通过, 存储用状态,
        // 查询用户权限.
        $rbac = Db::name('admin')
            ->alias('a')
            ->field('ru.id, rule')
            ->join('admin_role ar', 'a.id = ar.aid', $type = "LEFT")
            ->join('role ro', 'ar.rid = ro.id', $type = "LEFT")
            ->join('role_rule rr', 'rr.roid = ro.id', $type = "LEFT")
            ->join('rule ru', 'rr.ruid = ru.id', $type = "LEFT")
            ->where('a.id', $userInfo['id'])
            ->select();

        // 整理权限信息
        for($i = 0; $i<count($rbac); $i++){
            $rbacList[$i] = strtolower($rbac[$i]['rule']);
        }

        unset($_SESSION['admin']);
        $_SESSION['admin']['name'] = $name;
        $_SESSION['admin']['level'] = $level;
        $_SESSION['admin']['rbacList'] = $rbacList;
        $this->redirect(url('admin/Index/index'));
    }

    /*
     * 退出登录
     * */
    public function logout()
    {
        unset($_SESSION['admin']);
        $this->redirect(url('admin/Login/login'));

    }
}
